package com.chuhe.common.exception;

import com.chuhe.common.domain.vo.resp.ApiResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @Author: 楚河
 * @Date: 2025年05月02日14:25
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    /**
     * 指定异常
     * @Author: 楚河
     * @Date: 2025-05-02 15:44
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public ApiResult<?> methodArgumentNotValidException(MethodArgumentNotValidException e) {
        StringBuilder errorMsg = new StringBuilder();
        e.getBindingResult().getFieldErrors().forEach(x -> errorMsg
                .append(x.getField())
                .append(x.getDefaultMessage())
                .append(","));
        String message = errorMsg.toString();
        return ApiResult.fails(CommonErrorEnum.FREQUENCY_LIMIT.getCode(), message.substring(0, message.length() - 1));
    }
    /**
     * 业务异常（其他）
     * @Author: 楚河
     * @Date: 2025-05-02 15:45
     */
//    @ExceptionHandler(value = BusinessException.class)
//    public ApiResult<?> BusinessException(BusinessException e) {
//        log.info("Business Exception! The reason is:{}",e.getMessage());
//        return ApiResult.fail(e.errorCode,e.errorMsg);
//    }
    /**
     * 星空聊天室 业务异常
     * @Author: 楚河
     * @Date: 2025-05-12 22:29
     */
    @ExceptionHandler(value = BusinessException.class)
    public ApiResult<?> BusinessException(BusinessException e) {
        log.info("Business Exception! The reason is:{}",e.getInfo());
        return ApiResult.fails(e.code,e.info);
    }

    /**
     * 系统异常
     * @Author: 楚河
     * @Date: 2025-05-02 15:44
     */
    @ExceptionHandler(value = Throwable.class)
    public ApiResult<?> throwable(Throwable e) {
        log.error("system exception! The reason is:{}",e.getMessage());
        return ApiResult.fails(CommonErrorEnum.CODE_904);
    }

}
